package com.zhida.common.controller;

import com.zhida.common.handler.NonStaticResourceHttpRequestHandler;
import com.zhida.common.service.ResourcesService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static com.zhida.common.utils.StaticKeyUtil.CURRENT_PATH;

/**
 * Create by zhh 2024/7/27 12:37
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    @Resource
    ResourcesService resourcesService;

    public FileController(NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler) {
        this.nonStaticResourceHttpRequestHandler = nonStaticResourceHttpRequestHandler;
    }

    @RequestMapping("/getImage/{fileName}")
    public void readFile(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response){
//        获取该文件的绝对路径
        String activePath = CURRENT_PATH + "/" + resourcesService.getActivePath(fileName) + fileName;
        Path filePath = Paths.get(activePath);
        try {
            if (Files.exists(filePath)) {
                String mimeType = Files.probeContentType(filePath);
                if (!StringUtils.isEmpty(mimeType)) {
                    response.setContentType(mimeType);
                }
                request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
                nonStaticResourceHttpRequestHandler.handleRequest(request, response);
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            }
        } catch (IOException | ServletException e) {
            throw new RuntimeException(e);
        }
    }
}
